#include "project.h"

int cgiMain(int argc, const char *argv[])
{
	/*创建消息队列*/
	key_t key = 0; 
	if((key = ftok("/home/linux",'a')) == -1) 
	{ 
		perror("ftok"); 
		return -1; 
	}

	msqid = msgget(key,IPC_CREAT|0666); 
	if(msqid == -1) { 
		perror("msgget"); 
		return -1; 
	}
	

	/*创建共享内存*/
	if((key = ftok("/home/linux",'m')) == -1){ 
		perror("ftok"); 
		return -1; 
	}

	shmid = shmget(key,sizeof(msg_t),IPC_CREAT|0666); 
	if(shmid == -1){ 
		perror("shmid"); 
		return -1; 
	}
	
	/*映射共享内存地址空间*/
	shm_addr = (msg_t *)shmat(shmid,NULL,0); 
	if(shm_addr == (void *) -1){ 
		perror("shmat"); 
		return -1; 
	}
	
	/*创建信号灯集*/
	int semid = semget(key,2,IPC_CREAT|0666);

	/*初始化*/
	union semun sem;
	sem.val = 0;
	semctl(semid,1,SETVAL,sem);

	msg_t shm_data;
		
	msg.mtype = 2;
	msg.store_num = 1;
	msgsnd(msqid,&msg,sizeof(msg_t)-sizeof(long),0); 
	memset(&shm_data,0,sizeof(msg_t));

	/*p操作 等待共享内存写完*/
	p(semid,1);
	/*读取共享内存数据  核心消息为环境数据*/
	memcpy(&shm_data,shm_addr,sizeof(msg_t));
	/*V操作 释放共享内存使用权*/
	v(semid,0);
		
		/*将环境数据以网页形式输出*/

	while(1){
		printf("Content-type: text/html;charset=\"UTF-8\"\n\n");
		printf("<html>\n");

		printf("<head>");
		printf("<title>1号仓库环境信息</title>");
		printf("</head>");

		printf("<body bgcolor=\"#FFD700\">\n");

		printf("<center>");
		//printf("<h1> 1号仓库环境信息 </h1>");
		printf("</center>");

		printf("<br><br><br><br>");

		printf("<table border = \"1\" align=\"center\">");
		printf("<th> 温度 </th>");
		printf("<th> 湿度 </th>");
		printf("<th> 光照 </th>");
		
		printf("<tr>");
		printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %d </td>",shm_data.env_state_msg.tmp);
		printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %d </td>",shm_data.env_state_msg.hum);
		printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %d </td>",shm_data.env_state_msg.illu);

		printf("</tr>");
		printf("</table><br><br>");
			
		printf("<table border = \"1\" align=\"center\">");
		printf("<th> LED </th>");
		printf("<th> FAN </th>");
		printf("<th> BEEP </th>");
		
		printf("<tr>");
		if(shm_data.env_state_msg.led==1){
			printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %s </td>","ON");
		}else{
			printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %s </td>","OFF");		
		}
		if(shm_data.env_state_msg.fan==1){
			printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %s </td>","ON");
		}else{
			printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %s </td>","OFF");		
		}
		if(shm_data.env_state_msg.beep==1){
			printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %s </td>","ON");
		}else{
			printf("<td bgcolor=\"#ADFF2F\" width=\"50\" height=\"10\"> %s </td>","OFF");		
		}
		printf("</tr>");

		printf("</table><br><br>");
		printf("</body>\n");
		printf("</html>\n");			

		sleep(5);
		printf("<script>window.location.href = './one_store_env_view.cgi';</script>\n"); //跳转到设备控制界面
		return 0;

	}

}

